package org.txazo.music.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.txazo.music.commons.annotation.RequireLogin;
import org.txazo.music.util.AnnotationUtil;
import org.txazo.music.util.StringUtil;
import org.txazo.music.util.log.LoggerManager;
import org.txazo.music.vo.User;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 登录权限拦截器
 * 
 * @author Tu XiaoZhou
 * @since 2013-04-13
 * 
 */
public class LoginInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		LoggerManager.LOGGER_CONSOLE.debug("1111111");

		ActionProxy proxy = invocation.getProxy();
		Object action = invocation.getAction();

		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();

		RequireLogin require = AnnotationUtil.getFromMethedOrType(
				RequireLogin.class, action, proxy.getMethod());

		if (require != null) {
			LoggerManager.LOGGER_CONSOLE.debug("222222222");
			User user = (User) session.getAttribute("user");

			if (user == null) {
				LoggerManager.LOGGER_CONSOLE.debug("3333333");

				if (request.getMethod().equalsIgnoreCase("post")) {
					String referer = request.getHeader("referer");
					request.setAttribute("forward", referer);
				} else {
					String forward = request.getRequestURI();
					if (StringUtil.isNotEmpty(request.getQueryString())) {
						forward += "?" + request.getQueryString();
					}
					request.setAttribute("forward", forward);
				}

				LoggerManager.LOGGER_CONSOLE.debug("4444444444");
				return Action.LOGIN;
			}
		}

		return invocation.invoke();
	}

}
